"""
现代化UI组件

提供可复用的现代化UI组件
"""

import customtkinter as ctk
from typing import Callable, Optional, Union, List
from .themes import ModernTheme, ComponentStyles
import tkinter as tk
import math

class ModernButton(ctk.CTkButton):
    """现代化按钮组件"""
    
    def __init__(self, parent, text: str = "", variant: str = "primary", 
                 size: str = "md", icon: str = None, **kwargs):
        # 获取样式
        style = ComponentStyles.get_button_style(variant)
        
        # 设置尺寸
        if size == "sm":
            style["height"] = ModernTheme.SIZES['button_height_sm']
            style["font"] = ModernTheme.get_font('body_sm')
        elif size == "lg":
            style["height"] = ModernTheme.SIZES['button_height_lg']
        
        # 合并用户自定义样式
        style.update(kwargs)
        
        super().__init__(parent, text=text, **style)
        
        if icon:
            self.configure(text=f"{icon} {text}")

class ModernCard(ctk.CTkFrame):
    """现代化卡片组件"""
    
    def __init__(self, parent, title: str = "", padding: int = None, **kwargs):
        # 获取卡片样式
        style = ComponentStyles.get_card_style()
        style.update(kwargs)

        super().__init__(parent, **style)

        # 设置内边距
        if padding is None:
            padding = ModernTheme.SIZES['spacing_lg']

        # 主容器
        self.content_frame = ctk.CTkFrame(self, fg_color="transparent")
        self.content_frame.pack(fill="both", expand=True, padx=padding, pady=padding)
        
        # 标题
        if title:
            self.title_label = ctk.CTkLabel(
                self.content_frame,
                text=title,
                font=ModernTheme.get_font('heading_sm'),
                text_color=ModernTheme.get_color('text_primary')
            )
            self.title_label.pack(anchor="w", pady=(0, ModernTheme.SIZES['spacing_md']))
    
    def add_content(self, widget):
        """添加内容到卡片"""
        widget.pack(in_=self.content_frame, fill="x", pady=(0, ModernTheme.SIZES['spacing_sm']))

class ModernEntry(ctk.CTkEntry):
    """现代化输入框组件"""
    
    def __init__(self, parent, label: str = "", placeholder: str = "", 
                 validation: Callable = None, **kwargs):
        # 获取输入框样式
        style = ComponentStyles.get_input_style()
        if placeholder:
            style["placeholder_text"] = placeholder
        style.update(kwargs)
        
        # 创建容器
        self.container = ctk.CTkFrame(parent, fg_color="transparent")
        
        # 标签
        if label:
            self.label = ctk.CTkLabel(
                self.container,
                text=label,
                font=ModernTheme.get_font('body'),
                text_color=ModernTheme.get_color('text_primary'),
                anchor="w"
            )
            self.label.pack(fill="x", pady=(0, ModernTheme.SIZES['spacing_xs']))
        
        # 输入框
        super().__init__(self.container, **style)
        self.pack(fill="x")
        
        # 验证函数
        self.validation = validation
        if validation:
            self.bind("<KeyRelease>", self._validate)
        
        # 错误提示标签
        self.error_label = ctk.CTkLabel(
            self.container,
            text="",
            font=ModernTheme.get_font('caption'),
            text_color=ModernTheme.COLORS['error']
        )
    
    def _validate(self, event=None):
        """验证输入"""
        if self.validation:
            is_valid, message = self.validation(self.get())
            if not is_valid:
                self.configure(border_color=ModernTheme.COLORS['error'])
                self.error_label.configure(text=message)
                self.error_label.pack(fill="x", pady=(ModernTheme.SIZES['spacing_xs'], 0))
            else:
                self.configure(border_color=ModernTheme.get_color('border_medium'))
                self.error_label.pack_forget()
    
    def pack(self, **kwargs):
        """重写pack方法"""
        self.container.pack(**kwargs)
    
    def grid(self, **kwargs):
        """重写grid方法"""
        self.container.grid(**kwargs)

class ModernProgressBar(ctk.CTkProgressBar):
    """现代化进度条组件"""
    
    def __init__(self, parent, label: str = "", show_percentage: bool = True, **kwargs):
        # 创建容器
        self.container = ctk.CTkFrame(parent, fg_color="transparent")
        
        # 标签和百分比容器
        if label or show_percentage:
            self.header_frame = ctk.CTkFrame(self.container, fg_color="transparent")
            self.header_frame.pack(fill="x", pady=(0, ModernTheme.SIZES['spacing_xs']))
            
            if label:
                self.label = ctk.CTkLabel(
                    self.header_frame,
                    text=label,
                    font=ModernTheme.get_font('body'),
                    text_color=ModernTheme.get_color('text_primary')
                )
                self.label.pack(side="left")
            
            if show_percentage:
                self.percentage_label = ctk.CTkLabel(
                    self.header_frame,
                    text="0%",
                    font=ModernTheme.get_font('body'),
                    text_color=ModernTheme.get_color('text_secondary')
                )
                self.percentage_label.pack(side="right")
        
        # 进度条样式
        style = {
            "height": 8,
            "corner_radius": 4,
            "progress_color": ModernTheme.COLORS['primary'],
            "fg_color": ModernTheme.get_color('bg_tertiary')
        }
        style.update(kwargs)
        
        # 进度条
        super().__init__(self.container, **style)
        self.pack(fill="x")
        
        self.show_percentage = show_percentage
    
    def set(self, value: float):
        """设置进度值"""
        super().set(value)
        if hasattr(self, 'percentage_label') and self.show_percentage:
            self.percentage_label.configure(text=f"{int(value * 100)}%")
    
    def pack(self, **kwargs):
        """重写pack方法"""
        self.container.pack(**kwargs)

class ModernTabView(ctk.CTkTabview):
    """现代化标签页组件"""
    
    def __init__(self, parent, **kwargs):
        style = {
            "corner_radius": ModernTheme.SIZES['radius_md'],
            "border_width": ModernTheme.SIZES['border_width'],
            "border_color": ModernTheme.get_color('border_light'),
            "fg_color": ModernTheme.get_color('bg_card'),
            "segmented_button_fg_color": ModernTheme.get_color('bg_tertiary'),
            "segmented_button_selected_color": ModernTheme.COLORS['primary'],
            "segmented_button_selected_hover_color": ModernTheme.COLORS['primary_hover'],
            "text_color": ModernTheme.get_color('text_primary'),
            "text_color_disabled": ModernTheme.get_color('text_secondary')
        }
        style.update(kwargs)
        
        super().__init__(parent, **style)

class ModernSwitch(ctk.CTkSwitch):
    """现代化开关组件"""
    
    def __init__(self, parent, text: str = "", **kwargs):
        style = {
            "switch_width": 50,
            "switch_height": 25,
            "corner_radius": 12,
            "border_width": 2,
            "button_color": "white",
            "progress_color": ModernTheme.COLORS['primary'],
            "fg_color": ModernTheme.get_color('border_medium'),
            "text_color": ModernTheme.get_color('text_primary'),
            "font": ModernTheme.get_font('body')
        }
        style.update(kwargs)
        
        super().__init__(parent, text=text, **style)

class ModernCheckBox(ctk.CTkCheckBox):
    """现代化复选框组件"""
    
    def __init__(self, parent, text: str = "", **kwargs):
        style = {
            "checkbox_width": 20,
            "checkbox_height": 20,
            "corner_radius": 4,
            "border_width": 2,
            "checkmark_color": "white",
            "fg_color": ModernTheme.COLORS['primary'],
            "border_color": ModernTheme.get_color('border_medium'),
            "hover_color": ModernTheme.COLORS['primary_hover'],
            "text_color": ModernTheme.get_color('text_primary'),
            "font": ModernTheme.get_font('body')
        }
        style.update(kwargs)
        
        super().__init__(parent, text=text, **style)

class ModernScrollableFrame(ctk.CTkScrollableFrame):
    """现代化滚动框架组件"""
    
    def __init__(self, parent, **kwargs):
        style = {
            "corner_radius": ModernTheme.SIZES['radius_md'],
            "border_width": ModernTheme.SIZES['border_width'],
            "border_color": ModernTheme.get_color('border_light'),
            "fg_color": ModernTheme.get_color('bg_card'),
            "scrollbar_fg_color": ModernTheme.get_color('bg_tertiary'),
            "scrollbar_button_color": ModernTheme.get_color('border_medium'),
            "scrollbar_button_hover_color": ModernTheme.get_color('border_dark')
        }
        style.update(kwargs)
        
        super().__init__(parent, **style)

class StatusBadge(ctk.CTkLabel):
    """状态徽章组件"""
    
    def __init__(self, parent, text: str = "", status: str = "info", **kwargs):
        # 状态颜色映射
        status_colors = {
            "success": (ModernTheme.COLORS['success'], "white"),
            "warning": (ModernTheme.COLORS['warning'], "white"),
            "error": (ModernTheme.COLORS['error'], "white"),
            "info": (ModernTheme.COLORS['info'], "white"),
            "default": (ModernTheme.get_color('bg_tertiary'), ModernTheme.get_color('text_primary'))
        }
        
        bg_color, text_color = status_colors.get(status, status_colors["default"])
        
        style = {
            "text": text,
            "fg_color": bg_color,
            "text_color": text_color,
            "corner_radius": 12,
            "font": ModernTheme.get_font('caption'),
            "width": 60,
            "height": 24
        }
        style.update(kwargs)
        
        super().__init__(parent, **style)
